#!/usr/bin/env php
<?php
namespace base;

if (is_file($path = './vendor/composer/installed.json')) {
    $packages = json_decode(@file_get_contents($path), true);
    // Compatibility with Composer 2.0
    if (isset($packages['packages'])) {
        $packages = $packages['packages'];
    }

    $console = include_once './config/console.php';
    $commands = $console['commands'];

    $services = include_once './app/service.php';
    foreach ($packages as $package) {
        if (!empty($package['extra']['yoke']['command'])) {
            $commands = array_merge($commands, (array) $package['extra']['yoke']['command']);
        }

        if (!empty($package['extra']['yoke']['services'])) {
            $services = array_merge($services, (array) $package['extra']['yoke']['services']);
        }

        if (!empty($package['extra']['yoke']['config'])) {

            $installPath = './vendor/' . $package['name'] . DIRECTORY_SEPARATOR;
            $configDir = './config/';

            foreach ((array) $package['extra']['yoke']['config'] as $name => $file) {

                $target = $configDir . $name . '.php';
                $source = $installPath . $file;

                if (is_file($target) && !$force) {
                    print_r("File {$target} not exist!");
                    continue;
                }

                if (!is_file($source)) {
                    print_r("File {$source} not exist!");
                    continue;
                }

                copy($source, $target);
            }
        }
    }

    $console['commands']=array_map(function($value){
        return str_replace("\\","\\\\",$value);
    },$commands);

    $header = '// +----------------------------------------------------------------------'.PHP_EOL.'// | 控制台配置'.PHP_EOL.'// +----------------------------------------------------------------------'.PHP_EOL;
    $content = '<?php ' . PHP_EOL . $header . "return " . parseField($console). ';';
    file_put_contents('./config/console.php', $content);

    $header = '// 系统服务定义文件'.PHP_EOL.'// 服务在完成全局初始化之后执行'.PHP_EOL;
    $content = '<?php ' . PHP_EOL . $header . "return " . var_export($services, true) . ';';
    file_put_contents('./app/service.php', $content);

    echo 'Succeed!';
}

function parseField($fieldArr,$sj='')
{
    $schema = '['.PHP_EOL;
    foreach ($fieldArr as $key => $value) {
        if(is_array($value)){     
            $schema.=$sj.'    // 指令定义'.PHP_EOL.$sj.'    "'.$key.'"=>'.parseField($value,'    ').','.PHP_EOL;
        }else{
            $schema.=$sj.'    "'.$key.'"=>"'.$value.'",'.PHP_EOL;
        } 
    }

    $schema = trim($schema,',').$sj."]";

    return $schema;
}